import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/page/common/api/api_common.dart';
import 'package:tender_flutter/page/common/helper/data_manager.dart';
import 'package:tender_flutter/page/home/model/city_entity.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/utils/amap_location.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/toast.dart';
import 'package:tender_flutter/widgets/base_appbar.dart';
import 'package:tender_flutter/widgets/load_state_layout.dart';

class CityPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _CityPageState();
}

class _CityPageState extends State<CityPage> {
  /// 城市数据
  List<CityEntity> _cityDatas;

  /// 选中省索引
  int _pIndex = 0;

  /// 定位的城市信息
  CityEntity _locationCity;

  @override
  void initState() {
    super.initState();

    /// 定位当前城市
    AMapLocationUtils.startLocation((location, refresh) {
      if (location != null) {
        setState(() {
          _locationCity = location;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: ThemeColors.colorWhite,
        appBar: _topAppBar(),
        body: FutureBuilder(
            future: ApiCommon.getCityDatas(),
            builder: (BuildContext context,
                AsyncSnapshot<List<CityEntity>> snapshot) {
              if (snapshot.hasData) {
                _cityDatas = snapshot.data;
                return LoadStateLayout(
                  bgColor: ThemeColors.colorWhite,
                  state: LoadState.State_Success,
                  successWidget: _bodyContent(),
                );
              } else {
                return LoadStateLayout(
                  bgColor: ThemeColors.colorWhite,
                  state: LoadState.State_Loading,
                );
              }
            }));
  }

  Widget _topAppBar() {
    return BaseAppBar(
      context,
      Text("城市选择", style: FonStyle.navTextStyle()),
      backgroundColor: ThemeColors.colorWhite,
    );
  }

  Widget _bodyContent() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          height: ScreenAdapter.height(100),
          color: ThemeColors.colorType11,
          child: Row(
            children: <Widget>[
              SizedBox(width: ScreenAdapter.width(30)),
              Text("当前位置",
                  style: TextStyle(
                      color: ThemeColors.colorType1,
                      fontSize: ScreenAdapter.sp(32))),
              SizedBox(width: ScreenAdapter.width(40)),
              FlatButton(
                child: Text(_locationCity == null ? "定位中" : _locationCity.title,
                    style: TextStyle(
                        color: ThemeColors.colorType1,
                        fontSize: ScreenAdapter.sp(32),
                        fontWeight: FontWeight.bold)),
                onPressed: () {
                  if (_locationCity != null) {
                    /// 定位信息全局化
                    DataManager.instance.cityEntity = _locationCity;
                    LRouter.navigatorCtx(context).pop(_locationCity);
                  } else {
                    ToastUtils.show("定位中");
                  }
                },
              ),
            ],
          ),
        ),
        Expanded(
            child: Row(
          children: [
            Expanded(
              child: ListView.builder(
                  itemCount: _cityDatas.length,
                  itemBuilder: (context, index) {
                    return _getProvinceCell(_cityDatas[index], index);
                  }),
            ),
            Expanded(
              child: ListView.builder(
                  itemCount: _cityDatas[_pIndex].areas.length,
                  itemBuilder: (context, index) {
                    return _getCityCell(_cityDatas[_pIndex],
                        _cityDatas[_pIndex].areas[index], index);
                  }),
            )
          ],
        ))
      ],
    );
  }

  /// 省Cell
  Widget _getProvinceCell(model, index) {
    return InkWell(
      onTap: () {
        /// 刷新列表
        setState(() {
          _pIndex = index;
        });
      },
      child: ListTile(
        selectedTileColor: ThemeColors.colorType13,
        selected: _pIndex == index ? true : false,
        title: Text(
          model.title,
          style: TextStyle(
              color: ThemeColors.colorType1, fontSize: ScreenAdapter.sp(30)),
        ),
      ),
    );
  }

  /// 城市Cell
  Widget _getCityCell(proModel, cityModel, index) {
    return InkWell(
      onTap: () {
        CityEntity selectModel = cityModel.title == "全部" ? proModel : cityModel;

        /// 手动选择的城市信息全局化
        DataManager.instance.cityEntity = selectModel;
        LRouter.navigatorCtx(context).pop(selectModel);
      },
      child: ListTile(
        title: Text(
          cityModel.title,
          style: TextStyle(
              color: ThemeColors.colorType1, fontSize: ScreenAdapter.sp(30)),
        ),
      ),
    );
  }
}
